package net.stogi.dsper.ui.server.module.login;

import net.stogi.common.api.exception.BusinessException;
import net.stogi.common.gwt.dispatch.server.core.ActionHandler;
import net.stogi.common.gwt.dispatch.shared.exception.ActionException;
import net.stogi.dsper.api.service.UserService;
import net.stogi.dsper.ui.shared.module.login.GetUserByUsernameAction;
import net.stogi.dsper.ui.shared.module.login.GetUserByUsernameResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("DsperUi.Dispatch.GetUserByUsernameActionHandler")
public class GetUserByUsernameActionHandler implements ActionHandler<GetUserByUsernameAction, GetUserByUsernameResult> {

	private static final Logger log = LoggerFactory.getLogger(GetUserByUsernameActionHandler.class);

	@Autowired
	private UserService userService;

	@Override
	public GetUserByUsernameResult execute(GetUserByUsernameAction action) throws ActionException {
		log.trace("execute(): invoke [ action = '{}']", action);

		GetUserByUsernameResult result;

		try {
			result = new GetUserByUsernameResult(userService.getUserByUsername(action.getUsername()));
		}
		catch (BusinessException e) {
			throw new ActionException(e);
		}

		return result;
	}

	@Override
	public Class<GetUserByUsernameAction> getActionType() {
		return GetUserByUsernameAction.class;
	}

	@Override
	public void rollback(GetUserByUsernameAction action, GetUserByUsernameResult result) throws ActionException {}
}
